<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" type="image/x-icon" href="./data/favicon.ico">
    <!-- <script type="module" charset="UTF-8" src="./libs/three.js/Three.js"></script> -->
    <script type="text/javascript" src="./libs/dat.gui/dat.gui.min.js"></script>
    <style>
        body {
            margin: 0px;
            overflow: hidden;
        }

        #statsdiv {
            width: 200px;
            background-color: rebeccapurple;
            overflow: hidden;
        }
    </style>
    <title>threejs-lesson-15-material</title>
</head>

<body>
    <div id="puidu-webgk-output"></div>
    <div id="statsdiv"></div>
    <script type="module">
        import * as THREE from "./libs/three.js/three.js"
        import Stats from "./libs/stats.js/Stats.js"
        import {GLTFLoader} from './libs/three.js/jsm/loaders/GLTFLoader.js'
        // import {OBJLoader} from  "./libs/three.js/loaders/ObjectLoader.js"
        import {FBXLoader} from './libs/three.js/jsm/loaders/FBXLoader.js'
        import {MeshStandardMaterial} from './libs/three.js/materials/MeshStandardMaterial.js'
        import {OrbitControls} from './libs/three.js/jsm/controls/OrbitControls.js'
        import{RectAreaLightUniformsLib} from "./libs/three.js/jsm/lights/RectAreaLightUniformsLib.js"
        import{RectAreaLightHelper} from "./libs/three.js/jsm/helpers/RectAreaLightHelper.js"
        import{LightProbeGenerator} from './libs/three.js/jsm/lights/LightProbeGenerator.js'
        import {Lensflare,LensflareElement} from "./libs/three.js/jsm/objects/Lensflare.js"
        import {FontLoader} from './libs/three.js/jsm/loaders/FontLoader.js'

        import {TextGeometry} from "./libs/three.js/jsm/geometries/TextGeometry.js"
        var ctrl = new dat.GUI();
        //创建场景对象
        var scene = new THREE.Scene();
        //透视摄像机

        var prescamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        var orthcamera = new THREE.OrthographicCamera(-100,100,100,-100,-200,500);

        var textureLoader = new THREE.TextureLoader();
        var fontLoader = new FontLoader();

       var ground = creatgroung(scene);
       
        var currentcamera =prescamera;
        //相机位置
        prescamera.position.z = 100;
        prescamera.position.x = -30;
        prescamera.position.y = 20;

        orthcamera.position.z = -100;
        orthcamera.position.x = -30;
        orthcamera.position.y = 65;
        //渲染器
        var renderer = new THREE.WebGLRenderer();
        var orbitcontrol = new OrbitControls(currentcamera,renderer.domElement)
        //添加坐标轴
        var axes = new THREE.AxesHelper(50);
        axes.setColors(0xFF0000, 0x00FF00, 0x0000FF);
         scene.add(axes);
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.getElementById("puidu-webgk-output").appendChild(renderer.domElement)

        


        //创建渲染对象1
           var sphereGeo = new THREE.SphereGeometry(20,20,20)
           var meshMaterial = new THREE.MeshLambertMaterial({color:0xFFFF00});
           var sphereMesh = new THREE.Mesh(sphereGeo,meshMaterial);
           scene.add(sphereMesh);
         //属性控制

         var cubectrl = {
             visible:true,
             transparent:false,
             opacity:1,
             side:"front",
             depthTest:true,
             depthWrite:true,
             alphaTest:1,
             color:0xFFFF00,
             wireframe:false,
             map:true,
             reflectivity:1,
             reflectivityRatio:0.98,
             combine:"Multiply",
             alphaMap:true,
             envMap:true,
             emissive:0x0000000,
             emissiveIntensity:1,
            

         }
         var basicmaterialfolder = ctrl.addFolder("lambertmaterial属性");
         basicmaterialfolder.addColor(cubectrl,"color").onChange(color=>{
            meshMaterial.color = new THREE.Color(color);
         });
         basicmaterialfolder.addColor(cubectrl,"emissive").onChange(emissive=>{
            meshMaterial.emissive = new THREE.Color(emissive);
         });

         basicmaterialfolder.add(cubectrl,"emissiveIntensity",0,10).onChange(opacity=>{
            meshMaterial.emissiveIntensity= opacity;
         });

         textureLoader.load("./textures/brick_roughness.jpg",function(map){
            meshMaterial.emissiveMap=map;
            meshMaterial.needsUpdate=true;
         })
        //  var cubeguifolder = ctrl.addFolder("基础属性");

        //  cubeguifolder.add(cubectrl,"visible").onChange(visible=>{
        //     material.visible= visible;
        //  });
        //  cubeguifolder.add(cubectrl,"transparent").onChange(transparent=>{
        //     material.transparent= transparent;
        //  });
        //  cubeguifolder.add(cubectrl,"opacity",0,1).onChange(opacity=>{
        //     material.opacity= opacity;
        //  });
        //  cubeguifolder.add(cubectrl,"side",["front","back",'double']).onChange(side=>{
        //     switch(side){
        //            case "front":
        //            material.side =THREE.FrontSide;
        //            break;
        //            case "back":
        //            material.side =THREE.BackSide;
        //            break;
        //            case "double":
        //            material.side =THREE.DoubleSide;
        //            break;
        //         default:
        //            break;

        //     }
        //     material.needsUpdate =true;
        //  });
        //  cubeguifolder.add(cubectrl,"depthTest").onChange(depthTest=>{
        //     material.depthTest= depthTest;
        //  });
        //  cubeguifolder.add(cubectrl,"depthWrite").onChange(depthWrite=>{
        //     material.depthWrite= depthWrite;
        //  });
        //  cubeguifolder.add(cubectrl,"alphaTest",0,1).onChange(alphaTest=>{
        //     material.alphaTest= alphaTest;
        //  });
        // //添加纹理
        // var cubetexture=textureLoader.load('./textures/brick_roughness.jpg')
        // material.map=cubetexture;
        // var alphaMapTx = textureLoader.load("./textures/alphaMap.jpg")
        // material.alphaMap =alphaMapTx;
        // var cubetextures = createEnv();
        // material.envMap=cubetextures;
        // var basicmaterialfolder = ctrl.addFolder("basicmaterial属性");
        // basicmaterialfolder.addColor(cubectrl,"color").onChange(color=>{
        //     material.color = new THREE.Color(color);
        // });
        // basicmaterialfolder.add(cubectrl,"wireframe").onChange(wireframe=>{
        //     material.wireframe = wireframe;
        // });
        // basicmaterialfolder.add(cubectrl,"map").onChange(map=>{
        //     material.map=map? cubetexture:null;
        //     material.needsUpdate=true;
        // });
        // basicmaterialfolder.add(cubectrl,"envMap").onChange(envMap=>{
        //     material.envMap=envMap? cubetextures:null;
        //     material.needsUpdate=true;
        // });
        // basicmaterialfolder.add(cubectrl,"alphaMap").onChange(alphaMap=>{
        //     material.alphaMap=alphaMap? alphaMapTx:null;
        //     material.needsUpdate=true;
        // });
        // basicmaterialfolder.add(cubectrl,"reflectivity",0,1).onChange(e=>{
        //     material.reflectivity=e;
        // });
        // basicmaterialfolder.add(cubectrl,"reflectivityRatio",0,1).onChange(e=>{
        //     material.reflectivityRatio=e;
        // });
        // basicmaterialfolder.add(cubectrl,"combine",["Multiply","Add",'Mix']).onChange(combine=>{
        //     switch(combine){
        //            case "Multiply":
        //            material.combine =THREE.MultiplyOperation;
        //            break;
        //            case "Add":
        //            material.combine =THREE.AddOperation;
        //            break;
        //            case "Mix":
        //            material.combine =THREE.MixOperation;
        //            break;
        //         default:
        //            break;

        //     }
        //     material.needsUpdate =true;
        //  });

        

        var hemsipherelight = CreateHemispherelight();

        //告诉渲染器需要阴影效果
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是，没有设置的这个清晰 THREE.PCFShadowMap
        var directionalLight = new THREE.DirectionalLight("#ffffff");
        directionalLight.position.set(-100,100,-100);

        directionalLight.shadow.camera.near = 0.1; //产生阴影的最近距离
        directionalLight.shadow.camera.far = 1000; //产生阴影的最远距离
        directionalLight.shadow.camera.left = -500; //产生阴影距离位置的最左边位置
        directionalLight.shadow.camera.right = 500; //最右边
        directionalLight.shadow.camera.top = 500; //最上边
        directionalLight.shadow.camera.bottom = -500; //最下面

        //这两个值决定使用多少像素生成阴影 默认512
        directionalLight.shadow.mapSize.height = 2048;
        directionalLight.shadow.mapSize.width = 2048;



        //告诉平行光需要开启阴影投射
        directionalLight.castShadow = true;

         scene.add(directionalLight);
    
       

        currentcamera.lookAt(scene.position)
        //场景渲染
        //renderer.render(scene, prescamera);
        renderScene();

        function creatgroung(para_scene) {
            var groundgeometry = new THREE.PlaneGeometry(100, 100);
            var groungmaterial = new THREE.MeshBasicMaterial({ color: 0x777777 });
            var ground = new THREE.Mesh(groundgeometry, groungmaterial);
            ground.rotation.x = -0.5 * Math.PI;
            ground.position.y=-10;
            para_scene.add(ground);
            // 使平面就接收物体投掷过来的阴影
            ground.receiveShadow = true;

            return ground;
        };

        function creatgroung1(para_scene) {
            var groundgeometry = new THREE.BoxGeometry(1000,0.1, 1000);
            var groungmaterial = new THREE.MeshStandardMaterial({ color: 0xCCCCCC ,roughness:1.0,metal:1.0});
            var ground = new THREE.Mesh(groundgeometry, groungmaterial);
            // ground.rotation.x = -0.5 * Math.PI;
            para_scene.add(ground);
            // 使平面就接收物体投掷过来的阴影
            ground.receiveShadow = true;

            return ground;
        };

        function creatAmbientLight(para_scene) {
            var ambienLight = new THREE.AmbientLight(0xAAAAAA)
             // para_scene.add(ambienLight);
            return ambienLight;
        };

        function creatReactLight(){
            RectAreaLightUniformsLib.init();
            var rectLight = new THREE.RectAreaLight(0xFFFF00,5,4,4);
            rectLight.position.set(0,0,0);
            var reactlightHelper =new RectAreaLightHelper(rectLight);

            scene.add(rectLight);
            scene.add(reactlightHelper);
            return rectLight;
        }

        function CreateHemispherelight(){
            var hemishphtlight = new THREE.HemisphereLight(0xFFFFFF,0xFFFFFF,0.8);
            hemishphtlight.position.set(100,50,-100);
            scene.add(hemishphtlight);

            var hemispherelightctrobj={
                visible:true,
            }
            return hemishphtlight;
        }
        //场景渲染方法
        var gap = 0;
        function renderScene() {
          
            orbitcontrol.update();
            gap +=0.01;
            // pointlight.position.y = 25 + (20 * (Math.sin(gap)));
            // shereMesh.position.copy(pointlight.position);
            // cubrotating(cube, ctrlObj.rotationSpedd);
          
            // ambienLight.intensity =ctrlamblight.intensity;
          
            //遍历场景中所有对象
            // scene.traverse(child => {
            //     if (child instanceof THREE.Mesh && child != ground) {
            //         cubrotating(child, ctrlObj.rotationSpedd);
            //     }
            // })
            // cubjump(cube, gap);
            //  stats.update();

            window.requestAnimationFrame(renderScene);
            renderer.render(scene, currentcamera);

        }
       

        function cubrotating(param_geotry, speed) {
            param_geotry.rotation.x += speed;
            param_geotry.rotation.y += speed;
            param_geotry.rotation.z += speed;
        }
        function cubjump(param_geotry, speed) {
            speed = speed / Math.PI;
            param_geotry.position.x = 25 + (20 * (Math.sin(speed)));
            param_geotry.position.y = 6 + (20 * Math.abs((Math.cos(speed))));
            param_geotry.position.z = 6 + (-20 * Math.abs((Math.cos(speed))));
            //currentcamera.lookAt(param_geotry.position)
        }
        function removeFindCube(object) {
            if (object instanceof Mesh) {
                scene.remove(object);
            }
        }
        function creategrids(){
            console.log(ground.geometry.parameters);
            for(var i=0; i<ground.geometry.parameters.height/5;i++)
            {
                  for(var j =0;j<ground.geometry.parameters.width/5;j++){
                     var cubgeo = new THREE.BoxGeometry(4,4,4);
                     var cubmaterial = new THREE.MeshLambertMaterial();
                     cubmaterial.color = new THREE.Color(Math.random()*1.0,Math.random()*1.0,Math.random()*1.0);
                     var cub = new THREE.Mesh(cubgeo,cubmaterial);
                     cub.position.x=-47.25+i*5;
                     cub.position.y=0;
                     cub.position.z=-47.25+j*5;
                     scene.add(cub);

                  }
            }
        }

        function loadGltf(name){
          new GLTFLoader().setPath("model/").load(name,function(model){
             model.scene.scale.set(1.0,1.0,1.0);
             model.scene.traverse(child => {
                if (child.isMesh) {
                    child.castShadow=true;
                }
            })
              scene.add(model.scene);
          })
        }

        function loadOjb(name){
        //   new OBJLoader().setPath("model/").load(name,function(model){
        //     model.scene.scale.set(1.0,1.0,1.0);
        //       scene.add(model);
        //   })
        }
        function loadfbx(name){
          new FBXLoader().setPath("model/").load(name,function(model){
            //   model.scene.scale.set(1.0,1.0,1.0);
            console.log(model)
            model.traverse(child=>{
                if (child.isMesh) {
                    child.castShadow=true;
                }
            })
              scene.add(model);
          })
        }
        //创建环境贴图
        function createEnv(){
            var urls = ["./textures/posx.jpg","./textures/negx.jpg",
                "./textures/posy.jpg","./textures/negy.jpg",
                "./textures/posz.jpg","./textures/negz.jpg"];
            const  cubeTextureloader = new THREE.CubeTextureLoader();    
            const refCube = cubeTextureloader.load(urls);
            refCube.mapping = THREE.CubeRefractionMapping;
            refCube.format = THREE.RGBFormat;
            return refCube;

        }
        window.addEventListener("resize", onWindowResize, false);
        function onWindowResize() {
            currentcamera.aspect = window.innerWidth / window.innerHeight;
            currentcamera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }
    </script>
</body>

</html>